package com.zenithmind.coding.service.impl;

import com.zenithmind.coding.mapper.ProblemFavoriteMapper;
import com.zenithmind.coding.pojo.entity.Problem;
import com.zenithmind.coding.pojo.vo.ProblemVO;
import com.zenithmind.coding.service.ProblemFavoriteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 问题收藏服务实现类 - 遵循单一职责原则，专门处理问题收藏相关功能
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProblemFavoriteServiceImpl implements ProblemFavoriteService {

    private final ProblemFavoriteMapper problemFavoriteMapper;

    @Override
    public Boolean favoriteProblem(String problemId, String userId) {
        log.info("收藏问题: problemId={}, userId={}", problemId, userId);
        int result = problemFavoriteMapper.insertFavorite(problemId, userId);
        return result > 0;
    }

    @Override
    public Boolean unfavoriteProblem(String problemId, String userId) {
        log.info("取消收藏问题: problemId={}, userId={}", problemId, userId);
        int result = problemFavoriteMapper.deleteFavorite(problemId, userId);
        return result > 0;
    }

    @Override
    public Boolean checkFavoriteStatus(String problemId, String userId) {
        log.debug("检查收藏状态: problemId={}, userId={}", problemId, userId);
        int count = problemFavoriteMapper.checkFavoriteStatus(problemId, userId);
        return count > 0;
    }

    @Override
    public List<ProblemVO> getUserFavoriteProblems(String userId, Integer limit) {
        log.info("获取用户收藏问题: userId={}, limit={}", userId, limit);
        List<Problem> problems = problemFavoriteMapper.selectUserFavoriteProblems(userId, limit);
        return problems.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Integer batchFavoriteProblems(List<String> problemIds, String userId) {
        log.info("批量收藏问题: problemIds={}, userId={}", problemIds, userId);
        return problemFavoriteMapper.batchInsertFavorites(problemIds, userId);
    }

    @Override
    public Integer batchUnfavoriteProblems(List<String> problemIds, String userId) {
        log.info("批量取消收藏: problemIds={}, userId={}", problemIds, userId);
        return problemFavoriteMapper.batchDeleteFavorites(problemIds, userId);
    }

    @Override
    public Object getUserFavoriteStatistics(String userId) {
        log.info("获取用户收藏统计: userId={}", userId);
        return problemFavoriteMapper.selectUserFavoriteStatistics(userId);
    }

    @Override
    public List<Object> getUserFavoriteCategories(String userId) {
        log.info("获取用户收藏分类: userId={}", userId);
        return problemFavoriteMapper.selectUserFavoriteCategories(userId);
    }

    @Override
    public List<Object> getUserFavoriteDifficultyDistribution(String userId) {
        log.info("获取用户收藏难度分布: userId={}", userId);
        return problemFavoriteMapper.selectUserFavoriteDifficultyDistribution(userId);
    }

    @Override
    public List<ProblemVO> searchUserFavoriteProblems(String userId, String keyword, Integer limit) {
        log.info("搜索用户收藏问题: userId={}, keyword={}, limit={}", userId, keyword, limit);
        List<Problem> problems = problemFavoriteMapper.searchUserFavoriteProblems(userId, keyword, limit);
        return problems.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProblemVO> filterUserFavoritesByTags(String userId, List<String> tags, Integer limit) {
        log.info("按标签筛选用户收藏: userId={}, tags={}, limit={}", userId, tags, limit);
        List<Problem> problems = problemFavoriteMapper.selectUserFavoritesByTags(userId, tags, limit);
        return problems.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProblemVO> filterUserFavoritesByDifficulty(String userId, Integer difficulty, Integer limit) {
        log.info("按难度筛选用户收藏: userId={}, difficulty={}, limit={}", userId, difficulty, limit);
        List<Problem> problems = problemFavoriteMapper.selectUserFavoritesByDifficulty(userId, difficulty, limit);
        return problems.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public String exportUserFavoriteProblems(String userId, String format) {
        log.info("导出用户收藏列表: userId={}, format={}", userId, format);
        List<ProblemVO> problems = getUserFavoriteProblems(userId, null);

        // 简单的导出实现，实际项目中可以使用更复杂的导出逻辑
        if ("json".equalsIgnoreCase(format)) {
            // 返回JSON格式的字符串
            return problems.toString();
        } else if ("csv".equalsIgnoreCase(format)) {
            // 返回CSV格式的字符串
            StringBuilder csv = new StringBuilder();
            csv.append("ID,Title,Difficulty,Status\n");
            for (ProblemVO problem : problems) {
                csv.append(problem.getId()).append(",")
                   .append(problem.getTitle()).append(",")
                   .append(problem.getDifficultyName()).append(",")
                   .append(problem.getStatusName()).append("\n");
            }
            return csv.toString();
        } else {
            throw new IllegalArgumentException("不支持的导出格式: " + format);
        }
    }

    /**
     * 切换收藏状态
     */
    public Boolean toggleFavorite(String problemId, String userId) {
        log.info("切换收藏状态: problemId={}, userId={}", problemId, userId);
        if (checkFavoriteStatus(problemId, userId)) {
            return unfavoriteProblem(problemId, userId);
        } else {
            return favoriteProblem(problemId, userId);
        }
    }

    /**
     * 清理过期收藏
     */
    public void cleanExpiredFavorites(Integer days) {
        log.info("清理过期收藏: days={}", days);
        int result = problemFavoriteMapper.cleanExpiredFavorites(days);
        log.info("清理过期收藏完成: 删除{}条记录", result);
    }

    /**
     * 转换为VO
     */
    private ProblemVO convertToVO(Problem problem) {
        ProblemVO vo = new ProblemVO();
        vo.setId(problem.getId());
        vo.setTitle(problem.getTitle());
        vo.setDescription(problem.getDescription());
        vo.setDifficulty(problem.getDifficulty());
        vo.setTimeLimit(problem.getTimeLimit());
        vo.setMemoryLimit(problem.getMemoryLimit());
        vo.setStatus(problem.getStatus());
        vo.setCreateTime(problem.getCreateTime());
        vo.setUpdateTime(problem.getUpdateTime());
        
        // 设置额外信息
        setAdditionalInfo(vo);
        
        return vo;
    }

    /**
     * 设置额外信息
     */
    private void setAdditionalInfo(ProblemVO vo) {
        // 设置难度名称
        vo.setDifficultyName(getDifficultyName(vo.getDifficulty()));
        
        // 设置状态名称
        vo.setStatusName(getStatusName(vo.getStatus()));
        
        // 设置收藏状态为true（因为这些都是收藏的问题）
        // TODO: 如果ProblemVO有setFavorited方法，可以设置收藏状态
    }

    /**
     * 获取难度名称
     */
    private String getDifficultyName(Integer difficulty) {
        if (difficulty == null) return "未知";
        return switch (difficulty) {
            case 1 -> "简单";
            case 2 -> "中等";
            case 3 -> "困难";
            case 4 -> "专家";
            default -> "未知";
        };
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        if (status == null) return "未知";
        return switch (status) {
            case 0 -> "草稿";
            case 1 -> "已发布";
            case 2 -> "已下架";
            case 3 -> "审核中";
            case 4 -> "审核失败";
            default -> "未知";
        };
    }
}
